package com.zxlfysj.sort;

import java.util.Arrays;

/**
 * 基数排序
 *
 * @author yangshujing
 * @create 2020-08-18 21:06
 */
public class RadixSort {
    public static void main(String[] args) {
        int[] arr = {53, 3, 542, 748, 14, 214};
        radixSort(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void radixSort(int[] arr) {
        //得到数组中最大的数
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        //得到最大数有几位数
        int maxLength = (max + "").length();

        //十个桶，每个一维数组就是一个桶
        int[][] bucket = new int[10][arr.length];
        //记录每个桶放入的数据个数
        int[] bucketElementCounts = new int[10];

        for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
            for (int j = 0; j < arr.length; j++) {
                int digitOfElement = arr[j] / n % 10;//取出每个数的位数进行处理，从个位开始
                //放入对应的桶中
                bucket[digitOfElement][bucketElementCounts[digitOfElement]] = arr[j];
                bucketElementCounts[digitOfElement]++;
            }
            //按照桶的顺序，依次取出放入原来数组
            int index = 0;
            for (int k = 0; k < bucketElementCounts.length; k++) {
                if (bucketElementCounts[k] != 0) {
                    for (int m = 0; m < bucketElementCounts[k]; m++) {
                        arr[index++] = bucket[k][m];
                    }
                }
                bucketElementCounts[k] = 0;
            }
        }
    }
}
